package cloud.health.common.file.application.impl;

import cloud.health.common.file.application.FileService;
import cloud.health.common.file.domain.AbstractFile;
import cloud.health.common.file.domain.BinaryFile;
import cloud.health.common.file.domain.Request;
import cloud.health.common.file.infrastructure.R;
import cn.hutool.http.HttpStatus;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

import static cn.hutool.core.lang.Console.error;

/**
 * 文件下载
 */
@Slf4j
@Component
public class FileDownloadServiceImpl implements FileService {

    private AbstractFile bf;

    @Override
    public boolean filter(Request request) {
        return request.getHttp().getMethod().toLowerCase().equals("get")
                && Pattern.compile("/api/v0/.*?/.*?").matcher(request.getHttp().getUri()).find();
    }

    @Override
    public void handle(Request request) {
        if (bf == null) {
            bf = BinaryFile.findFile(request);
        }
        if (request.completed()) {
            if (!bf.isSuccess()) {
                R r = R.fail(HttpStatus.HTTP_FORBIDDEN, "访问资源不存在");
                request.getContext().writeAndFlush(Unpooled.wrappedBuffer(r.response()));
                return;
            }
            bf.download(request.getContext());
            bf.close();
            // request.getContext().close();
        }
    }

}